//
//  SCPhotoCell.m
//  PhotoAlbum
//
//  Created by Chao Sheng on 2021/12/1.
//

#import "SCPhotoCell.h"
#import "SCHitButton.h"

@interface SCPhotoCell()

@property (nonatomic, strong) SCHitButton *selectBtn;

@end

@implementation SCPhotoCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    [self.contentView addSubview:self.photoImageView];
    [self.photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [self.contentView addSubview:self.selectBtn];
    [self.selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@3);
        make.right.equalTo(@-3);
        make.width.height.equalTo(@20);
    }];
}

#pragma mark - 后期优化
//存在图片显示不正确的问题后期优化
- (void)setPhotoModel:(SCPhotoModel *)photoModel {
    _photoModel = photoModel;
    if (self.photoModel.tempImage) {
        self.photoImageView.image = self.photoModel.tempImage;
    } else {
        sc_weak(self);
        CGSize targetSize = CGSizeMake(self.frame.size.width*1.7, self.frame.size.height*1.7);
        self.photoImageView.image = nil;
        [SCPhotoTools getPhotoForPHAsset:_photoModel.asset size:targetSize completion:^(UIImage * _Nonnull image,PHAsset *asset) {
            if (asset==weakself.photoModel.asset) {
                weakself.photoImageView.image = image;
                weakself.photoModel.tempImage = image;
            }
        }];
    }
    
    if (_photoModel.isSelected) {
        
        self.selectBtn.selected = true;
        self.selectBtn.backgroundColor = sc_Blue;
        NSString *count = [NSString stringWithFormat:@"%ld",_photoModel.selectedIndex];
        [self.selectBtn setTitle:count forState:UIControlStateSelected];
        
    } else {
        
        self.selectBtn.selected = false;
        self.selectBtn.backgroundColor = [UIColor clearColor];
        
    }
    
    
}

- (void)setManager:(SCPhotoManager *)manager {
    _manager = manager;
}

#pragma mark - action
//选中和取消选中的数据处理
- (void)selectAction {
        
    self.selectBtn.userInteractionEnabled = false;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.selectBtn.userInteractionEnabled = true;
    });

    self.selectBtn.selected = !self.selectBtn.selected;
    
    if(self.selectBtn.selected) {
        
        if (self.manager.photoSelectedMax==self.manager.selectedArray.count) {
            self.selectBtn.selected = false;
            [MBProgressHUD showSCHudText:[NSString stringWithFormat:@"最多选择%ld张",self.manager.photoSelectedMax]];
            return;
        }
        
        self.selectBtn.backgroundColor = sc_Blue;
        self.photoModel.isSelected = self.selectBtn.selected;
        [self.manager.selectedArray addObject:self.photoModel];
        
        NSString *count = [NSString stringWithFormat:@"%ld",self.manager.selectedArray.count];
        [self.selectBtn setTitle:count forState:UIControlStateSelected];
        
        [self.selectBtn.layer addAnimation:[self setAnimation] forKey:nil];
        
    } else {
        
        self.selectBtn.backgroundColor = [UIColor clearColor];
        self.photoModel.isSelected = self.selectBtn.selected;
        self.photoModel.selectedIndex = 0;
        if ([self.manager.selectedArray containsObject:self.photoModel]) {
            [self.manager.selectedArray removeObject:self.photoModel];
        }
    }
    
    //每次选择后都更新序号
    for (NSInteger i = 0; i < self.manager.selectedArray.count ; i++) {
        SCPhotoModel *model = self.manager.selectedArray[i];
        model.selectedIndex = i+1;
    }
    
    if (self.scSelectedCompltion) {
        self.scSelectedCompltion(self.photoModel);
    }
}

#pragma mark - 懒加载
- (UIImageView *)photoImageView {
    if (!_photoImageView) {
        _photoImageView = [[UIImageView alloc] init];
        _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
        _photoImageView.clipsToBounds = YES;
        _photoImageView.userInteractionEnabled = true;
    }
    return _photoImageView;
}

- (UIButton *)selectBtn {
    if (!_selectBtn) {
        _selectBtn = [SCHitButton buttonWithType:UIButtonTypeCustom];
        [_selectBtn setImage:[UIImage sc_bundleImageNamed:@"LGQ-image-unselected"] forState:UIControlStateNormal];
        [_selectBtn setImage:[UIImage new] forState:UIControlStateSelected];
        [_selectBtn addTarget:self action:@selector(selectAction) forControlEvents:UIControlEventTouchUpInside];
        _selectBtn.layer.cornerRadius = 10;
        _selectBtn.layer.masksToBounds = true;
        _selectBtn.userInteractionEnabled = true;
        _selectBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [_selectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [_selectBtn setTitle:@"" forState:UIControlStateNormal];
    }
    return _selectBtn;
}

- (CAAnimation*)setAnimation {
    CABasicAnimation *a = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    a.fromValue = @(1);
    a.toValue = @(1.2);
    a.duration = 0.1;
    a.fillMode = kCAFillModeForwards;
    a.removedOnCompletion = false;
    
    CABasicAnimation *b = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    b.fromValue = @(1.2);
    b.toValue = @(0.8);
    b.duration = 0.15;
    b.fillMode = kCAFillModeForwards;
    b.removedOnCompletion = false;
    b.beginTime = 0.1;
    
    CABasicAnimation *c = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    c.fromValue = @(0.8);
    c.toValue = @(1);
    c.duration = 0.1;
    c.fillMode = kCAFillModeForwards;
    c.removedOnCompletion = false;
    c.beginTime = 0.2;
    
    CAAnimationGroup *gruop = [CAAnimationGroup animation];
    gruop.animations = @[a,b,c];
    
    return gruop;
}

@end
